var jsonObj;
function init(){
	if(haveInventory==true){
		$('.buy-main').show();
		$('.buy-car').show();
		$('.arr-tellme').hide();
	}else{
		$('.buy-main').hide();
		$('.buy-car').hide();
		$('.arr-tellme').show();
	}
	$('.present').hide();
	
	chkAddOnProductUp();
	chkAddOnProductDown();
	$('.pdtab > li > a').each(function(){
		$(this).click(function(){
			$('.pdtab > li > a').each(function(){
				$(this).removeClass('pdtab-f');
			});
			$(this).addClass('pdtab-f');
		});
	});
	
	var anchorSplit=window.location.href.split('#');
	if(anchorSplit.length>1){
		var anchor=anchorSplit[1];
		if(anchor=='productInfo'){
			$('#j_tabs').tabs('select', 0);
			$('.pdtab > li > a').each(function(i){
				$(this).removeClass('pdtab-f');
				if(i==0){
					$(this).addClass('pdtab-f');
				}
			});
		}else if(anchor=='productqaa'){
			$('#j_tabs').tabs('select', 1);
			$('.pdtab > li > a').each(function(i){
				$(this).removeClass('pdtab-f');
				if(i==1){
					$(this).addClass('pdtab-f');
				}
			});
		}else if(anchor=='productMustRead'){
			$('#j_tabs').tabs('select', 2);
			$('.pdtab > li > a').each(function(i){
				$(this).removeClass('pdtab-f');
				if(i==2){
					$(this).addClass('pdtab-f');
				}
			});
		}
	}
}

function chkAddOnProductUp(){
	$(':input[name="addOnProduct"]').each(function(){
		$(this).click(function(){
			if($(this).attr('checked')){
				$(this).parent().parent().addClass('buymore-f');
			}else{
				$(this).parent().parent().removeClass('buymore-f');
			}
			chkedAddonProductDown();
		});
		
		if($(this).attr('checked')){
			$(this).parent().parent().addClass('buymore-f');
		}else{
			$(this).parent().parent().removeClass('buymore-f');
		}
	});
}
function chkedAddOnProductUp(){
	$(':input[name="addOnProduct"]').each(function(){
		if($(this).attr('checked')){
			$(this).parent().parent().addClass('buymore-f');
		}else{
			$(this).parent().parent().removeClass('buymore-f');
		}
	});
}
function chkedAddonProductDown(){
	$('.addOnProductB').each(function(){
		var id=$(this).attr('id');
		var index=id.split('_')[1];
		if($(this).attr('checked')){
			$('#purchaseinnerbox_'+index).attr('class', 'purchaseinnerbox_focus');
		}else{
			$('#purchaseinnerbox_'+index).attr('class', 'purchaseinnerbox');
		}
		chkedAddOnProductUp();
	});
}
function chkAddOnProductDown(){
	$('.addOnProductB').each(function(){
		$(this).click(function(){
			var id=$(this).attr('id');
			var index=id.split('_')[1];
			if($(this).attr('checked')){
				$('#purchaseinnerbox_'+index).attr('class', 'purchaseinnerbox_focus');
			}else{
				$('#purchaseinnerbox_'+index).attr('class', 'purchaseinnerbox');
			}
			chkedAddOnProductUp();
		});
		var id=$(this).attr('id');
		var index=id.split('_')[1];
		if($(this).attr('checked')){
			$('#purchaseinnerbox_'+index).attr('class', 'purchaseinnerbox_focus');
		}else{
			$('#purchaseinnerbox_'+index).attr('class', 'purchaseinnerbox');
		}		
	});
}
function ie7Disabled(){
	if ($.browser.msie && parseFloat($.browser.version) == 7) {
		$("option:disabled").css('color', 'graytext');
        $("select").find("[disabled]").addClass("disabled").removeAttr("disabled");
        $("select").change(function(){
            var selected = $(this).val();
            var disabled = $(this).find("[value="+selected+"]").hasClass("disabled");
            if (disabled) {
	            	alertDialog("","此属性已售完,无法选择");
                $(this).find("option:first").attr("selected","selected");
            }
        });
    }
}



function initSpec(){
	if(productType!='6'){
		//$('#spec').append('<option value="">商品属性</option>');
		//for(i=0;i<specs.length;i++){
		//	if(inventory[i]==0){
		//		$('#spec').append("<option disabled=\"disabled\" value=\""+specs[i]+"\">"+specNames[i]+"-已售完</option>");
		//	}else{
		//		$('#spec').append("<option value=\""+specs[i]+"\">"+specNames[i]+"</option>");
		//	}
		//}
		initSpecDefaultQty();
	}else{
		$('#spec').attr('value', specs[0]);
	}
}
function initSpecDefaultQty(){
	
	$('#qty').children().each(function(){
		$(this).remove();
	});
	//for(i=0;i<1;i++){
		if(haveInventory){
			$('#qty').append("<option value=\"\">1</option>");
		}else{
			$('#qty').append("<option value=\"\">0</option>");
		}
	//}
}
function changeInventory(specId){
	ie7Disabled();
	var rowAt;
	for(i=0;i<specs.length;i++){
		if(specId==specs[i]){
			rowAt=i;
			break;
		}
	}
	
	var min=minPOQ[rowAt];
	var max=parseInt(maxPOQ[rowAt],10);
	if(parseInt(maxPOQ[rowAt],10) > parseInt(inventory[rowAt],10)){
		max=inventory[rowAt];
	}
	if(haveInventory){
		$('#qty').children().each(function(){
			$(this).remove();
		});
		//$('#qty').append('<option value="">0</option>');
		for(i=min;i<=max;i++){
			if(inventory[rowAt]==0 || max<min){
				$('#qty').append("<option disabled=\"disabled\" value=\""+i+"\">"+i+"</option>");
			}else{
				$('#qty').append("<option value=\""+i+"\">"+i+"</option>");
			}
		}
	}
	//if(soldInventory[rowAt]>10){			
	//if(parseInt((soldInventory[rowAt] + hotSaleInventory[rowAt]),10) >10){
	//	$('.saled').html('(热销 <strong class="txt-rd">'+parseInt((soldInventory[rowAt] + hotSaleInventory[rowAt]),10)+'</strong> 件!)');
		//$('.saled').html('(热销 <strong class="txt-rd">'+soldInventory[rowAt]+'</strong> 件!)');
	//}else{
	//	$('.saled').html("");
	//}
	
}
function toAddCart3(){
	if(nmCount<productPickQty){
		alertDialog('选购商品', '请选择'+productPickQty+'件');
	}else{
		toAddCartDetail('addOnProductNm');
	}
	return false;
}
function toAddCart2(){

	toAddCartDetail('addOnProductB');
	return false;
}
function toAddCart(){
	toAddCartDetail('addOnProduct');
}
function toAddCartDaphne(){
	toAddCartDetail('addOnProductDaphne');
}
function toAddCartDetail(addOnProductClass){
	var error="";
	if($('#type').attr('value')=='1'){
		error+="预购商品只能直接购买！\r\n";
	}else{
		if($('#spec').attr('value')==''){
			error+="请选择商品属性！\r\n";
		}else if($('#qty').attr('value')==''){
			error+="请选择数量！\r\n";
		}else if($('#qty').attr('value')=='0'){
			error+="本属性商品已经售完！\r\n";
		}
	}
	if(error!=''){
		alertDialog('选购商品', error);
		return;
	}
	var itemNo="itemNo:\""+$("#productId").attr('value')+"\",";
	var specNo="specNo:\""+$("#spec").attr('value')+"\",";
	var qty="qty:\""+$("#qty").attr('value')+"\",";
	var categoryPath="";
	var z=getParameter('z');
	if(z!=''){
		categoryPath="categoryPath:\""+z+"\",";
	}else{
		categoryPath="categoryPath:\""+$("#categoryPath").attr('value')+"\",";
	}
	var type="type:\""+$("#type").attr('value')+"\",";
	var webpath="webpath:\"/"+$("#webpath").attr("value")+"/shopping/addCart.do?\",";
	var presents="presents:[";
	var present="";
	$('.presents').each(function(i){
		present=buildJson(present, $(this), $("#qty").attr('value'), i);
		
	});
	presents+=present;
	presents+="]";
	
	var addOns="addOns:\"";
	var obj="";
	$('.'+addOnProductClass).each(function(){
		if($(this).attr('checked')){
			var saddOnProd = $(this).val().split('_');
			var sSpecId = $('select#selectSs_'+saddOnProd[0]).val();
			if(sSpecId =='' || sSpecId ==null || sSpecId=='请选择'){
				$(":input[value="+$(this).val()+"]").attr('checked', false);
				error = '请选择商品属性';
				return;
			}
			var newValue = saddOnProd[0]+"_"+sSpecId;
			for(var i = 2 ; i < saddOnProd.length ; i++){
				newValue += '_'+saddOnProd[i];
			}
			$(":input[value="+$(this).val()+"]").val(newValue);
			obj=buildJson(obj, $(this));
		}
	});
	if(error!=''){
		alertDialog('加购商品', error);
		return;
	}
	addOns+=obj;
	addOns+="\"";
	var json="{";
	json+=itemNo;
	json+=specNo;
	json+=qty;
	json+=categoryPath;
	json+=type;
	json+=webpath;
	json+=presents;
	json+=",";
	json+=addOns;
	json+="}";
	eval("jsonObj="+json);
	if($.cookie("_1.100.AS")=='EDM'){
		var amount = $('.infocontent-price>b').eq(0).text();
		//$("#edmscript").load('http://edm.yaodian100.com/cgi-bin19/buyrate?Amount='+amount.substring(1,amount.length)+'&type=0&category=YD_CART&subcategory='+itemNo+'&quantity='+qty);
		$("#edmscript").html('<IMG src="http://edm.yaodian100.com/cgi-bin19/buyrate?Amount='+amount.substring(1,amount.length)+'&type=0&category=YD_CART&subcategory='+$("#productId").attr('value')+'&quantity='+$("#qty").attr('value')+'" width="1" height="1">');
	}
	$.post("/ecmall/nonMember/checkLogin.do",{},nonMemberTimeLimitCartCallback,"json");
}
function nonMemberTimeLimitCartCallback(result){//非會員點限時搶購商品加入購物車
	if(result.split('#')[0]=='needToActivate' || result.split('#')[0]=='waitActivate'){
		if ( hasTlProduct == "true" ){
			content='<div class="alert-caution"><p><b class="txt-rd">限时秒杀仅限会员购买！</b><br>立即<a href="/ecmall/toreg.do">加入会员</a>您可马上享受优惠！</p><div align="center"><a href="javascript:showNonmemberDialog(\'' + result + '\');closeDialog();" class="btn-mid" onfocus="blur()">登录或注册</a><a href="javascript:closeDialog();" class="btn-mid">关闭</a></div></div>';
			openDialog('活动信息', content,360,160);
		}else{
			addCart(jsonObj);
		}
	}else{
		addCart(jsonObj);
	}
}
function syncAddOnProduct(){
	$('.addOnProduct').each(function(){
		var obj=this;
		$(obj).click(function(){
			if($(obj).attr('checked')){
				var sSpecId = $('select#selectSs_'+$(obj).attr('value').split('_')[0]).val();
				if(sSpecId =='' || sSpecId ==null || sSpecId=='请选择'){
					$(obj).attr('checked', false);
					alertDialog('讯息','请先选择属性');
					return;
				}
			}
			$(":input[value="+$(obj).attr('value')+"]").attr('checked', $(obj).attr('checked'));
		});
	});
	$('.addOnProductB').each(function(){
		var obj=this;
		$(obj).click(function(){
			if($(obj).attr('checked')){
				var sSpecId = $('select#selectSs_'+$(obj).attr('value').split('_')[0]).val();
				if(sSpecId =='' || sSpecId ==null || sSpecId=='请选择'){
					$(obj).attr('checked', false);
					alertDialog('讯息','请先选择属性');
					return;
				}
			}
			$(":input[value="+$(obj).attr('value')+"]").attr('checked', $(obj).attr('checked'));
		});
	});
}
function loginForward(){
	var url=loginUrl;
	location.href=url;
}
var redirect_url = '';
var not_member_redirect_url = '';
function loginForwardRedirect(){
	location.href=fullUrl+'/tologin.do?redirect_url='+encodeURIComponent(redirect_url);
}
function notMemberloginForwardRedirect(){
	location.href=fullUrl+'/nonMember/tologin.do?redirect_url='+encodeURIComponent(not_member_redirect_url);
}
function toBuy(addOnProductClass,daphne){
	if(productType=='6'){
		if(nmCount<productPickQty){
			alertDialog('选购商品', '请选择'+productPickQty+'件');
			return false;
		}
	}
	var error="";
	if($('#spec').attr('value')==''){
		error+="请选择商品属性！\r\n";
	}else if($('#qty').attr('value')==''){
		error+="请选择数量！\r\n";
	}else if($('#qty').attr('value')=='0'){
		error+="本属性商品已经售完！\r\n";
	}
	if(error!=""){
		alertDialog('选购商品', error);
	}else{
		var itemNo=$("#productId").attr('value');
		var specNo=$("#spec").attr('value');
		var qty=$("#qty").attr('value');
	
		var categoryPath="";
		var z=getParameter('z');
		if(z!=''){
			categoryPath=z;
		}else{
			categoryPath=$("#categoryPath").attr('value');
		}
		var type=$("#type").attr('value');
		var webpath=$("#webpath").attr("value");
		var presents="[";
		var present="";
		$('.presents').each(function(i){
			present=buildJson(present, $(this), qty, i);
		});
		presents+=present;
		presents+="]";
		
		var addOns="\"";
		var obj="";
		$('.'+addOnProductClass).each(function(){
			if($(this).attr('checked')){
				var saddOnProd = $(this).val().split('_');
				var sSpecId = $('select#selectSs_'+saddOnProd[0]).val();
				if(sSpecId =='' || sSpecId ==null || sSpecId=='请选择'){
					$(":input[value="+$(this).val()+"]").attr('checked', false);
					error = '请选择商品属性';
					return;
				}
				var newValue = saddOnProd[0]+"_"+sSpecId;
				for(var i = 2 ; i < saddOnProd.length ; i++){
					newValue += '_'+saddOnProd[i];
				}
				$(":input[value="+$(this).val()+"]").val(newValue);
				obj=buildJson(obj, $(this));
			}
		});
		if(error!=''){
			alertDialog('加购商品', error);
			return;
		}	
		addOns+=obj;
		addOns+="\"";
		if ( daphne == "true" ){
			$("#toBuyForm").attr("action","/ecmall/shopping/orderBuyDaphne.do");
		}
			
		document.toBuyForm.itemNo.value=itemNo;
		document.toBuyForm.specNo.value=specNo;
		document.toBuyForm.qty.value=qty;
		document.toBuyForm.categoryPath.value=categoryPath;
		document.toBuyForm.type.value=type;
		document.toBuyForm.webpath.value=webpath;
		if(presents=='[]'){
			document.toBuyForm.presents.value='null';
		}else{
			document.toBuyForm.presents.value=presents;
		}
		if(addOns=='[]'){
			document.toBuyForm.addOns.value='';
		}else{
			document.toBuyForm.addOns.value=addOns;
		}
		var buyPath;
		if ( daphne == "true" )
			buyPath = "orderBuyDaphne";
		else
			buyPath = "orderBuyNow";
		redirect_url = fullUrl+'/shopping/' + buyPath + '.do?itemNo=' + itemNo + "&specNo=" + specNo + "&categoryPath="
		+ categoryPath + "&type=" + type + "&presents=" + presents + "&qty=" +qty + "&addOns=" + addOns;
		not_member_redirect_url = fullUrl+'/shopping/' + buyPath + '.do?itemNo=' + itemNo + "&specNo=" + specNo + "&categoryPath="
		+ categoryPath + "&type=" + type + "&presents=" + presents + "&qty=" +qty + "&addOns=" + addOns;		
		if(!isLogin()){
			loginForwardRedirect();
			//if ( hasTlProduct == "true")
			//	loginTimeLimitDialog('您尚未登入', '您尚未登入耀点100！<br><b class="txt-rd">限时秒杀限会员购买！</b>', 'loginForwardRedirect()',360,200);
			//else
			//	loginPromptDialog('您尚未登入', '您尚未登入耀点100！', 'loginForwardRedirect()','notMemberloginForwardRedirect()',360,200);
		}else{
			$.post("/ecmall/nonMember/checkLogin.do",{},nonMemberTimeLimitCallback,"json");
		}
	}
	return false;
}
function buildJson(obj, jObj, mainQty, i){
	if(obj!=""){
		obj+=",";
	}
	
	objs=jObj.attr('value').split('_');
	var specNo=$('select#selectSs_'+objs[0]).val();
	if(productType!='6'){
	obj+=objs[0]+(specNo==null?"":(";"+specNo));
	}else{
	var index=jObj.attr('id').replace('addOnProductNm_','');
	var spec=$('#selectSs_'+index).attr('value');
	specNo=spec;
	obj+=objs[0]+";"+specNo;
	}

	return obj;
}
function moveBottom(index){
	var anchor="pluspurchase";
	location.href="#";
	location.href="#"+anchor;
	var objDiv = document.getElementById("purchaseBox");
	if(index>4){
		objDiv.scrollTop = objDiv.scrollHeight;
	}else{
		objDiv.scrollTop = 0;
	}
}
function isLogin(){
	var cookies=document.cookie.split(';');
	for(i=0;i<cookies.length;i++){
		theCookie=cookies[i].split('=');
		if(theCookie[0].replace(' ', '')=='_1.100.D'){
			if(theCookie[1]!=''){
				return true;
			}else{
				return false;
			}
		}
	}
	return false;
}


function nonMemberTimeLimitCallback(result){//非會員點限時搶購商品立即購買、達芙妮
	if(result.split('#')[0]=='needToActivate' || result.split('#')[0]=='waitActivate'){
		if ( hasTlProduct == "true" ){
			content='<div class="alert-caution"><p><b class="txt-rd">限时秒杀仅限会员购买！</b><br>立即<a href="/ecmall/toreg.do">加入会员</a>您可马上享受优惠！</p><div align="center"><a href="javascript:showNonmemberDialog(\'' + result + '\');closeDialog();" class="btn-mid" onfocus="blur()">登录或注册</a><a href="javascript:closeDialog();" class="btn-mid">关闭</a></div></div>';
			openDialog('活动信息', content,360,160);
		}else{
			document.toBuyForm.submit();
		}
	}else{
		if ( hasTlProduct == "true" ){
			$.post("/ecmall/shopping/checkOrderBuyTlp.do",{
				  productId:$("#productId").val()},
						function callback(result){	
						if(result == '2'){	
							document.toBuyForm.submit();
						}else if(result == '1'){	
							content='<div class="alert-caution"><p>每档限时秒杀活动，<b class="txt-rd">同一帐号限购一项商品。</b><br>您可参加下一档秒杀活动喔，谢谢您！</p><div align="center"><a href="javascript:closeDialog();" class="btn-mid">关闭</a></div></div>';
							openDialog('活动信息', content,370,'auto');	
						}},"json");
		}else{
			//document.toBuyForm.submit();
			$.post("/ecmall/shopping/orderBuyNowJson.do",$("#toBuyForm").serialize(),checkSpecInvCallback,"json");
			
		}
	}
}

function checkSpecInvCallback(actionResult){
	if(actionResult != "" && actionResult !='OK'){// 主商品數量檢查
		//alertDialog("库存不足",result,"",400,200);
		if(actionResult.indexOf('赠品 ')>0){
			$("#chkPinvyDialog > p").eq(0).html(actionResult);
			$('#chkPinvyDialog').dialog('destroy');
			$('#chkPinvyDialog').dialog({
				closeOnEscape: false,
				open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
				bgiframe: true,
				width:380,
				modal: true
			});
		}else{
			//alert(result);
			$("#chkProdInvDialog > p").eq(0).html(actionResult);
			$('#chkProdInvDialog').dialog('destroy');
			$('#chkProdInvDialog').dialog({
				closeOnEscape: false,
				open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
				bgiframe: true,
				width:380,
				modal: true
			});
			//alertDialog("库存不足",result,"",400,200);
		}
	}else{
		document.toBuyForm.submit();
	}
}